using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UIElements;
using Button = UnityEngine.UI.Button;
using Image = UnityEngine.UI.Image;

public class DialogController : MonoBehaviour
{
    private static DialogController instance;
   
    [SerializeField]private Player player;
    [SerializeField]private TextAsset text;
    [SerializeField]private Image sprite;
    [SerializeField]private TMP_Text nameText;
    [SerializeField]private TMP_Text dialogText;

    [SerializeField]private List<Sprite> sprites = new List<Sprite>();

    private Dictionary<string, Sprite> imageDic = new Dictionary<string, Sprite>();

    //当前对话索引值
    public int dialogIndex = 0;

    
    private string[] rows;


    [SerializeField] private Button nextButton;

    [SerializeField]private GameObject optionButtion;
    [SerializeField]private Transform buttonGroup;
    [SerializeField] private GameObject canvas;

    private bool isTyping;
    
    
    private string currentText = "";
    private Animator anim;
    
    private void Awake()
    {
        imageDic["八奈见杏菜"] = sprites[0];
        imageDic["温水和彦"] = sprites[1];
        if(instance != null) Destroy(instance);
        instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {   
        ReadText(text);
        ShowDialogRow();
        anim = player.GetComponent<Animator>();

    }

    private void UpdateText(string name,string text)
    {
        nameText.text = name;
        currentText = text;
        StartCoroutine(TypeText(text));
        
    }

    IEnumerator TypeText(string text)
    {
        isTyping = true;
        string ct = "";
        float typeSpeed = 0.1f;
        foreach (var letter in text)
        {
            ct += letter;
            dialogText.text = ct;
            yield return new WaitForSeconds(typeSpeed);
        }
        isTyping = false;
    }

    private void UpdateImage(string name)
    {
        sprite.sprite = imageDic[name];
    }

    private void ReadText(TextAsset textAsset)
    {
        if (textAsset != null)
        {
            rows = textAsset.text.Split('\n');
        }
    }

    private void ShowDialogRow()
    {
        for (int i = 0; i < rows.Length; i++)
        {
            string row = rows[i];
            string[] cells = row.Split(',');
            if ( cells[0] == "#" &&int.Parse(cells[1]) == dialogIndex)
            {
                nextButton.gameObject.SetActive(true);
                UpdateText(cells[2],cells[3]);
                UpdateImage(cells[2]);
                dialogIndex = int.Parse(cells[4]);
                break;
            }else if (cells[0] == "%" && int.Parse(cells[1]) == dialogIndex)
            {
                nextButton.gameObject.SetActive(false);
                GenerateOption(i);
            }else if (cells[0] == "END" && int.Parse(cells[1]) == dialogIndex)
            {   
                //player.enabled = true;
                canvas.SetActive(false);
                
                Debug.Log("剧情结束");
            }
        }
        
    }

    public void OnClickContinue()
    {
        if (isTyping)
        {
            StopAllCoroutines();
            dialogText.text = currentText;
            isTyping = false;
        }
        else
        {
            ShowDialogRow();
        }
    }

    private void GenerateOption(int index)
    {
        string[] cells = rows[index].Split(',');
        if (cells[0] == "%")
        {
            GameObject button = Instantiate(optionButtion,buttonGroup);
            button.GetComponentInChildren<TMP_Text>().text = cells[3];
            button.GetComponent<Button>().onClick.AddListener(
                delegate
                    {
                        OnselectClick(int.Parse(cells[4]));
                    }
                );
            GenerateOption(index + 1);
        }
    }

    public void OnselectClick(int id)
    {
        dialogIndex = id;
        
        for (int i = 0; i < buttonGroup.childCount; i++)
        {
            Destroy(buttonGroup.GetChild(i).gameObject);
        }
        ShowDialogRow();
        
    }


    public void OptionEffect(string effect, int param, string target)
    {
        
    }
}
